package com.ldk.admin.controller;

import com.ldk.admin.common.Status;
import com.ldk.base.framework.util.FileUtil;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {

    /**
     * 上传图片接口
     *
     * @param module   图片存放的文件夹 默认'images'
     * @param hasThumb 是否生产缩略图
     * @param hasRoot  返回的地址是否包括根地址
     * @param file
     * @return
     * @paramtoWeixin 是否将图片上传到微信素材里面
     * @paramcatId 微信分类ID 用来获取该微信分类的配置信息
     */
    @ResponseBody
    @RequestMapping(value = "/image", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public UploadResult uploadImage(@RequestParam(value = "module", required = true, defaultValue = "images") String module,
                                    @RequestParam(value = "hasThumb", required = false, defaultValue = "false") Boolean hasThumb,
                                    @RequestParam(value = "hasRoot", required = false, defaultValue = "false") Boolean hasRoot,
                                    MultipartFile file) {
        UploadResult result = new UploadResult();
        try {
            if (file != null && !file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                String ext = FileUtil.getFileExtention(fileName);
                if (!".png".equalsIgnoreCase(ext) &&
                        !".jpg".equalsIgnoreCase(ext) &&
                        !".gif".equalsIgnoreCase(ext) &&
                        !".jpeg".equalsIgnoreCase(ext)) {
                    result.AddError("图片格式错误");

                    return result;
                }
                Map<String, String> map = saveImage(module, file, hasThumb, hasRoot);
                if (map.isEmpty() || !map.containsKey("link") || StringUtils.isEmpty(map.get("link"))) {
                    result.AddError("图片上传失败");
                } else {
                    result.AddOk(map.get("link"), map.get("thumb"));
                }
            }
        } catch (Exception e) {
            result.AddError("上传图片失败");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/file")
    public UploadResult file(@RequestParam(value = "module", required = true) String module,
                             @RequestParam(value = "hasRoot", required = false, defaultValue = "false") Boolean hasRoot,
                             MultipartFile file) {
        UploadResult result = new UploadResult();
        try {
            if (file != null && !file.isEmpty()) {

                String fileName = file.getOriginalFilename();
                String ext = FileUtil.getFileExtention(fileName);
                if (!".dat".equalsIgnoreCase(ext) &&
                        !".DAT".equalsIgnoreCase(ext) &&
                        !".xls".equalsIgnoreCase(ext) &&
                        !".xlsx".equalsIgnoreCase(ext) &&
                        !".doc".equalsIgnoreCase(ext) &&
                        !".docx".equalsIgnoreCase(ext) &&
                        !".txt".equalsIgnoreCase(ext) &&
                        !".apk".equalsIgnoreCase(ext) &&
                        !".ipa".equalsIgnoreCase(ext)) {
                    result.AddError("文件格式错误");

                    return result;
                }
                Boolean useNewName = true;
                if (ext.equalsIgnoreCase(".apk") || ext.equalsIgnoreCase(".ipa")) {
                    useNewName = false;
                }
                Map<String, String> map;

                map = saveFile(module, file, hasRoot, useNewName);


                if (map.isEmpty() || !map.containsKey("link") || StringUtils.isEmpty(map.get("link"))) {
                    result.AddError("文件上传失败");
                } else {
                    result.AddOk(map.get("link"), "");
                }
            }
        } catch (Exception e) {
            result.AddError("文件上传失败");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/remove")
    public UploadResult remove(@RequestParam(value = "module", required = true) String module,
                               @RequestParam(value = "file", required = true) String file) {
        UploadResult rst = new UploadResult();

        try {
            if (!StringUtils.isEmpty(module) &&
                    !StringUtils.isEmpty(file) &&
                    file.lastIndexOf(".") > 0) {
                String imgFile = file;
                if (file.lastIndexOf("/") >= 0) {
                    imgFile = file.substring(file.lastIndexOf("/") + 1);
                }
                module = module.replace("\\", "/");
                String filePath = getImagePath() + "/" + module;
                if (!filePath.endsWith("/")) {
                    filePath += "/";
                }
                filePath = filePath.replace("\\", "/");
                filePath += imgFile;
                Boolean deleted = FileUtil.deleteFile(filePath);
                if (deleted) {
                    rst.AddOk("", "");
                } else {
                    rst.AddError("删除文件失败");
                }
            }
        } catch (Exception e) {
            rst.AddError("删除文件失败");
        }

        return rst;
    }

    public class UploadResult {

        public UploadResult() {

        }

        public UploadResult(Status status, String link, String thumb) {
            this.status = status;
            this.link = link;
            this.thumb = thumb;
        }

        public void AddError(String message) {
            this.status = Status.ERROR;
            this.link = "";
            this.thumb = "";
            this.message = message;
        }

        public void AddOk(String link, String thumb) {
            this.status = Status.OK;
            this.link = link;
            this.thumb = thumb;
        }

        private Status status;
        private String link;
        private String thumb;
        private String message;

        public String getLink() {
            return link;
        }

        public void setLink(String link) {
            this.link = link;
        }

        public String getThumb() {
            return thumb;
        }

        public void setThumb(String thumb) {
            this.thumb = thumb;
        }

        public Status getStatus() {
            return status;
        }

        public void setStatus(Status status) {
            this.status = status;
        }

        /**
         * @return the message
         */
        public String getMessage() {
            return message;
        }

        /**
         * @param message the message to set
         */
        public void setMessage(String message) {
            this.message = message;
        }

    }

}
